package com.cn.wanix.servlet;

import com.alibaba.fastjson.JSON;
import com.cn.wanix.model.LayEditModel;
import com.cn.wanix.model.ProductModel;
import com.cn.wanix.model.ResultModel;
import com.cn.wanix.service.ProductService;
import com.cn.wanix.service.impl.ProductServiceImpl;
import com.cn.wanix.util.Path;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

@WebServlet("/upload")
public class UploadImgServlet extends HttpServlet {
    private static String filename = null;
    private String url = "";
    private String directory = "/loadImg/";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//        存放文件
        DiskFileItemFactory factory = new DiskFileItemFactory();
//        解析文件---前段传递过来的文件
        ServletFileUpload upload = new ServletFileUpload(factory);
//        factory.setSizeThreshold(1024 * 1024);
        List items = null;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
//        Iterator迭代器和list区别？
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
//            判断当前是否为普通表单
            if (!item.isFormField()) {
// 根据时间戳创建头像文件
                filename = System.currentTimeMillis() + Path.SPLIT + item.getName();
                System.out.println(req.getContextPath());
                String path = req.getServletContext().getRealPath("");

                /*File f = new File(getServletContext().getRealPath("upload"));*/
                File f = new File(path, directory);

                if (!f.exists()) {
                    f.mkdir();
                }
                File webDirectory = new File(path.split("out")[0] + "/web/", directory);
                if (!webDirectory.exists()) {
                    webDirectory.mkdir();
                }
//                String imgsrc = f + "/" + filename;
                File file = new File(f, filename);
                File webFile = new File(webDirectory, filename);
                url = directory + filename;
// 复制文件
                InputStream is = item.getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                FileOutputStream outputStream = new FileOutputStream(webFile);
                byte b[] = new byte[1024 * 1024];
                int length = 0;
                while (-1 != (length = is.read(b))) {
                    outputStream.write(b, 0, length);
                    fos.write(b, 0, length);

                }
                fos.flush();
                fos.close();
            } else {
                System.out.println(item.getFieldName());
                String value = item.getString();
                value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                System.out.println(value);
            }
        }
//        需要得到图片路径

        ResultModel resultModel = new ResultModel(0, "", new LayEditModel(url));
//        5.返回页面状态
//        PrintWriter out = resp.getWriter();
        String resJSON = JSON.toJSONString(resultModel);     // 转换为json
        resp.getWriter().print(resJSON); // 输出
    }

}
